<template>
  <div>
    <el-upload
      :action="minioUploadUrl"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">仅允许上传 JPG/PNG 格式的文件，文件大小不超过 10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="currentImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { minioUploadUrl } from '@/api/updatefile'

export default {
  name: 'SingleUpload',
  props: {
    value: String
  },
  computed: {
    currentImageUrl() {
      return this.value || ''
    },
    imageName() {
      if (this.currentImageUrl) {
        return this.currentImageUrl.substring(this.currentImageUrl.lastIndexOf("/") + 1)
      }
      return null
    },
    fileList() {
      // Create a new array to avoid direct mutation
      if (this.currentImageUrl) {
        return [{
          name: this.imageName,
          url: this.currentImageUrl
        }]
      }
      return []
    },
    showFileList() {
      return !!this.currentImageUrl
    }
  },
  data() {
    return {
      dialogVisible: false,
      minioUploadUrl
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    handleRemove() {
      this.emitInput('')
    },
    handlePreview() {
      if (this.currentImageUrl) {
        this.dialogVisible = true
      }
    },
    handleUploadSuccess(res) {
      if (res && res.data && res.data.url) {
        this.emitInput(res.data.url)
      } else {
        this.$message.error('上传失败: Invalid response')
        this.emitInput('')
      }
    },
    handleUploadError(err) {
      console.error('上传失败:', err)
      this.$message.error('上传失败')
      this.emitInput('')
    }
  }
}
</script>
<style scoped>
.el-upload__tip {
  margin-top: 10px;
}
</style>